<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CPaymentRequestForm">
          <a-row>
            <a-col :span="12">
              <a-form-item label="项目" v-bind="validateInfos.projectId" id="CPaymentRequestForm-projectId" name="projectId">
                 <j-dict-select-tag showSearch="true"
                  v-model:value="formData.projectId"
                  dictCode="c_project_application,project_name,id"
                  placeholder="请选择项目"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CPaymentRequestForm-subProjectId" name="subProjectId">
                 <j-dict-select-tag showSearch="true"
                  v-model:value="formData.subProjectId"
                  dictCode="c_sub_project,sub_project_name,id"
                  placeholder="请选择子项目"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="分包商ID" v-bind="validateInfos.contractorId" id="CPaymentRequestForm-contractorId" name="contractorId">
                 <j-dict-select-tag showSearch="true"
                  v-model:value="formData.contractorId"
                  dictCode="c_contractor_info,contact_name,id"
                  placeholder="请选择分包商ID"
                  allow-clear
                />
              </a-form-item>
            </a-col>



            <a-col :span="12">
              <a-form-item label="银行名称" v-bind="validateInfos.bankName" id="CPaymentRequestForm-bankName" name="bankName">
                <a-input v-model:value="formData.bankName" placeholder="请输入银行名称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="开户行" v-bind="validateInfos.branchName" id="CPaymentRequestForm-branchName" name="branchName">
                <a-input v-model:value="formData.branchName" placeholder="请输入开户行" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="银行卡号" v-bind="validateInfos.accountNumber" id="CPaymentRequestForm-accountNumber" name="accountNumber">
                <a-input v-model:value="formData.accountNumber" placeholder="请输入银行卡号" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="开户人名称"
                v-bind="validateInfos.accountHolderName"
                id="CPaymentRequestForm-accountHolderName"
                name="accountHolderName"
              >
                <a-input v-model:value="formData.accountHolderName" placeholder="请输入开户人名称" allow-clear></a-input>
              </a-form-item>
            </a-col>


            <a-col :span="12">
              <a-form-item  label="申请打款记录" v-bind="validateInfos.applyId" id="CPaymentRequestForm-applyId" name="applyId">

                 <j-dict-select-tag showSearch="true"
                  disabled="true"
                  v-model:value="formData.applyId"
                  dictCode="c_payment_request_apply,apply_title,id"
                  placeholder="请选择子申请打款记录"
                  allow-clear
                />
              </a-form-item>
            </a-col>

            <a-divider >打款信息</a-divider >
            <a-col :span="12">
              <a-form-item label="本次打款金额" v-bind="validateInfos.paymentAmount" id="CPaymentRequestForm-paymentAmount" name="paymentAmount">
                <a-input-number v-model:value="formData.paymentAmount" placeholder="请输入本次打款金额" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="付款方式" v-bind="validateInfos.paymentMethods" id="CPaymentRequestForm-paymentMethods" name="paymentMethods">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.paymentMethods" dictCode="payment_methods" placeholder="请选择付款方式" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="付款凭证" v-bind="validateInfos.paymentAffix" id="CPaymentRequestForm-paymentAffix" name="paymentAffix">
                <j-upload v-model:value="formData.paymentAffix"  dragger="true"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"></j-upload>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="付款类型" v-bind="validateInfos.paymentType" id="CPaymentRequestForm-paymentType" name="paymentType">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.paymentType" dictCode="payment_type" placeholder="请选择付款类型" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注" v-bind="validateInfos.remark" id="CPaymentRequestForm-remark" name="remark">
                <a-textarea v-model:value="formData.remark" :rows="4" placeholder="请输入备注" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="打款日期" v-bind="validateInfos.paymentDate" id="CPaymentRequestForm-paymentDate" name="paymentDate">
                <a-date-picker
                  placeholder="请选择打款日期"
                  v-model:value="formData.paymentDate"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-divider >关联发票</a-divider >
            </a-col>

            <a-col :span="24">
              <a-form-item label="发票" v-bind="validateInfos.invoiceId" id="CProjectApplicationForm-invoiceId" name="invoiceId">
                <a-select
                  v-model:value="invoiceSplit"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="请选择发票"
                  :options="invoiceSplitList"
                  @change="handleChange"
                ></a-select>
              </a-form-item>
            </a-col>

            根据


          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,getLoadinvoiceSplit } from '../CPaymentRequest.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JSelectMultiple from '../../../components/Form/src/jeecg/components/JSelectMultiple.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const invoiceSplitList = ref()
  const invoiceMap = ref()
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    projectId: '',
    subProjectId: '',
    contractorId: '',
    paymentDate: '',
    paymentAmount: undefined,
    paymentMethods: '',
    paymentAffix: '',
    paymentType: '',
    remark: '',
    bankName: '',
    branchName: '',
    accountNumber: '',
    accountHolderName: '',
    applyId:''
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
   // projectId: [{ required: true, message: '请输入项目ID!' }],
   // subProjectId: [{ required: true, message: '请输入子项目!' }],
   // contractorId: [{ required: true, message: '请输入分包商ID!' }],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });
      //赋值
      Object.assign(formData, tmpData);
    });

    const param = {
      'projectId':record.projectId,
      'subProjectId':record.subProjectId
    };
    loadinvoiceSplit(param)
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  async function loadinvoiceSplit(param){
    invoiceSplitList.value=[]
    invoiceMap.value={}
   const rest =  await getLoadinvoiceSplit(param)
    for(var i=0;i<rest.length;i++){
      const result = rest[i]
      invoiceSplitList.value.push({
        "value":result.id,
        "label":result.title,
      })
      invoiceMap[result.id] = result;
    }

  }

  defineExpose({
    add,
    edit,
    submitForm,
    invoiceSplitList,
    loadinvoiceSplit,
    invoiceMap,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
